// 高阶组件

import React from 'react'
import ReactDOM from 'react-dom'

// 创建高阶组件，他会接收一个参数，表示被渲染的组件
function withMouse(WrappedComponent){
    // 该组件提供复用的状态逻辑
    class Mouse  extends React.Component{
        // 鼠标状态
        state={
            x:0,
            y:0
        }
        handleMouse= e=>{
            this.setState({
                x:e.clientX,
                y:e.clientY
            })
        }

        componentDidMount(){
            window.addEventListener('mousemove',this.handleMouse)
        }

        componentWillUnmount(){
            window.removeEventListener('mousemove',this.handleMouse)
        }

        render(){
            return <WrappedComponent {...this.state}{...this.props}></WrappedComponent>
        }
    }

    // 设置displayName
    Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
    return Mouse
}

function getDisplayName (WrappedComponent){
    return WrappedComponent.displayName || WrappedComponent.name || "Component"
}


// 测试高阶组件
const Position = props=>(
    <p>
        鼠标当前的位置是:x:{props.x},y:{props.y}
    </p>
)

// 跟随移动
const Cat = props =>(
    <img src="https://ts1.cn.mm.bing.net/th/id/R-C.193db300d38700a7a909b87caf9967e6?rik=vkFwSbprY2UeHw&riu=http%3a%2f%2fimg.mm4000.com%2ffile%2fe%2fcd%2f4b2ddb2b72.jpg%3fdown&ehk=w%2bnvBGL%2fGdlWz2oP7MA%2bSd5uuFhWBYvEdY9frXUa6BE%3d&risl=&pid=ImgRaw&r=0"
    alt='猫' style={{width:'50px',height:"50px",position:'absolute',top:props.y,left:props.x}}></img>
)

// 获取增强后的组件
const MousePosition = withMouse(Position)

// 获取增强后的组件
const MouseCat = withMouse(Cat)

// 父组件
class App extends React.Component{
    render(){
        return(
                <div>
                    <h1> 高阶组件</h1>
                    <MousePosition name='王'/>
                    <MouseCat/>
                </div>
        )
    }


}





ReactDOM.render(<App/>,document.getElementById('root'))